var isMouseDown, instance, width, height, top, left, saturation, lightness;
var windowTop = 0

function setWindowTop(num = 0) {
	windowTop = num
}

function getNode(views, node) {
	return new Promise((resolve, reject) => {
		views.select(node).boundingClientRect(data => {
			if(data) {
			  resolve(data)
			} else {
			  reject('节点错误')
			}
		}).exec();
	})
}

async function touchstart(e, _this, views) {
	//解决往上冒泡的问题
	_this.firstTouch()
	isMouseDown = e.type === 'mousedown'
	var touches= e.touches[0] || e
	var x = touches.clientX
	var y = touches.clientY
	var rect = await getNode(views, '.color-panel')
	width = rect.width
	height = rect.height
	top = rect.top - windowTop
	left = rect.left
	//获取相对坐标
	x = x - left
	y = y - top
	//修正滑块超出边界
	x = x >= width ? width : x <= 0 ? 0 : x
	y = y >= height ? height : y <= 0 ? 0 : y
	//计算饱和度和亮度
	saturation = parseInt((x / width) * 100);
	lightness = parseInt((1 - y / height) * 100);
	//设置滑块位置
	_this.setPostion(x, y)
}

async function touchmove(e, _this, views) {
	if (e.type === 'mousemove' && !isMouseDown) return;
	var touches=e.touches[0] || e
	var x = touches.clientX
	var y = touches.clientY

	//获取相对坐标
	x = x - left
	y = y - top

	//修正滑块超出边界
	x = x > width ? width : x < 0 ? 0 : x
	y = y > height ? height : y < 0 ? 0 : y

	//计算饱和度和亮度
	saturation = parseInt((x / width) * 100);
	lightness = parseInt((1 - y / height) * 100);
	//设置滑块位置
	_this.setPostion(x, y)
	_this.emitEvent({ saturation: saturation, lightness: lightness })
}

async function touchend(e, _this, views) {
	if (!isMouseDown && (e.type === 'mouseup' || e.type === 'mouseleave')) return;
	if (e.type === 'mouseleave' || e.type === 'mouseup') {
		var touches=e.touches[0] || e
		var x = touches.clientX
		var y = touches.clientY
		var rect = await getNode(views, '.color-panel')
		width = rect.width
		height = rect.height
		top = rect.top - windowTop
		left = rect.left
		//获取相对坐标
		x = x - left
		y = y - top

		//修正滑块超出边界
		x = x > width ? width : x < 0 ? 0 : x
		y = y > height ? height : y < 0 ? 0 : y

		//计算饱和度和亮度
		saturation = parseInt((x / width) * 100);
		lightness = parseInt((1 - y / height) * 100);
		//设置滑块位置
		_this.setPostion(x, y)
	}
	isMouseDown = false
	_this.emitEvent({ saturation: saturation, lightness: lightness })
}


export default {
	touchstart: touchstart,
	touchmove: touchmove,
	touchend: touchend,
	setWindowTop: setWindowTop
}